package com.wang.jmonkey.interceptor.handler.result;

import cn.hutool.core.collection.CollUtil;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * @Description 拦截器中返回异常结果的责任链配置
 * @Author HeJiawang
 * @Date 2021/5/21 10:46
 */
public class ExceptionResultHandlerManager implements ExceptionResultHandler {

    private int index = 0;

    private List<ExceptionResultHandler> list = CollUtil.newArrayList();

    private ApplicationContext context;

    public ExceptionResultHandlerManager(ApplicationContext context) {
        this.context = context;
    }

    @PostConstruct
    private void init() {
        Map<String, ExceptionResultHandler> map = context.getBeansOfType(ExceptionResultHandler.class);
        if (CollUtil.isEmpty(map)) return;

        map.entrySet().forEach( entry -> {
            if (!(entry.getValue() instanceof ExceptionResultHandlerManager)) {
                list.add(entry.getValue());
            }
        });
    }


    @Override
    public Object result(Class<?> resultType, String errorMessage, ExceptionResultHandler handler) {
        if (index == list.size()) return null;  // 不在责任链处理能力中，返回null

        ExceptionResultHandler h = list.get(index++);
        return h.result(resultType , errorMessage , handler);
    }
}
